//package com.nk.system.filter;
//
//import java.io.IOException;
//import java.net.MalformedURLException;
//import java.net.URL;
//import java.util.Date;
//
//import javax.servlet.FilterChain;
//import javax.servlet.FilterConfig;
//import javax.servlet.ServletContext;
//import javax.servlet.ServletException;
//import javax.servlet.ServletRequest;
//import javax.servlet.ServletResponse;
//
//import org.apache.commons.lang.StringUtils;
//import org.apache.log4j.Logger;
//import org.apache.xmlrpc.XmlRpcException;
//import org.apache.xmlrpc.client.XmlRpcClient;
//import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
//import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.web.context.WebApplicationContext;
//import org.springframework.web.context.support.WebApplicationContextUtils;
//
//import com.accellence.kbond.authentication.AuthenticationHelper;
//import com.accellence.kbond.authentication.PasswordConstants;
//import com.accellence.kbond.authentication.UserProfile;
//import com.accellence.kbond.bean.MiddlewareResponse;
//import com.accellence.kbond.bean.userprofile.UserProfileBean;
//import com.accellence.kbond.service.UserProfileService;
//import com.nk.system.utils.CommonHelper;
//import com.nk.system.utils.UI_Constants;
//
//import javax.servlet.Filter;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
///**
// * 
// * 0 Get locale and user token
// * 1 Get logged user
// * 2 Check role is system admin or IBM support 
// * 3 Is login first time
// * 4 Is login after first time more than 30 days
// * 5 Is login after last signin more than 60 days
// * 6 Check password is expired, get remaining day
// * ? Set user access into DB and session
// *
// */
//public class PasswordPolicyFilter implements Filter {
//
//	private static final Logger log = Logger.getLogger(PasswordPolicyFilter.class);
//
//	private static final String URI_KBOND_CHANGEPASSWORD = "/page/manageuser_initPasswordUser.action";
//	private static final String URI_KBOND_CHANGEPASSWORD_SUBMIT = "/page/manageuser_savePasswordUser.action";
//	private static final String URI_KBOND_LOAD_ACTIVE_ALERT = "/page/getAlertData_loadActiveAlert.action";
//	
//	private UserProfileService userProfileService;
//	
//	public void destroy() {
//		// TODO Auto-generated method stub
//		
//	}
//	
//	private MiddlewareResponse callMiddleware(HttpSession session,UserProfileBean userProfileBean){
//		XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
//		MiddlewareResponse result = new MiddlewareResponse();
//		try {
//			ServletContext context = session.getServletContext();
//			String url = StringUtils.defaultIfEmpty((String) context.getInitParameter("CALL_MIDDLEWARE"), "http://localhost:8080/kbondxmlrpc/xmlrpc.do");
//			config.setServerURL(new URL(url));
//			config.setEnabledForExceptions(true);
//			config.setEnabledForExtensions(true);
//		} catch (MalformedURLException e1) {
//
//			e1.printStackTrace();
//		}
//		XmlRpcClient client = new XmlRpcClient();
//		client.setTransportFactory(new XmlRpcCommonsTransportFactory(client));
//		client.setConfig(config);
//		Object[] params = new Object[] { userProfileBean };
//		try {
//			result = (MiddlewareResponse) client.execute("userProfileService.updateUserProfileForLogin", params);
//			System.out.println("result=" + result);
//		} catch (XmlRpcException e) {
//			log.info(e, e);
//		} catch (Exception e) {
//			log.info(e, e);
//		}
//		return result;
//	}
//
//	public void doFilter(ServletRequest arg0, ServletResponse arg1,
//			FilterChain arg2) throws IOException, ServletException {
//		// TODO Auto-generated method stub
//		log.info("**********Post-Authentication was run**********");
//		HttpServletRequest request = (HttpServletRequest)arg0;
//		HttpServletResponse response = (HttpServletResponse)arg1;
//		log.info("Request Session ID: "+request.getRequestedSessionId());
//
//		//Get user token
//		UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) request.getUserPrincipal();
//		log.info("UserPrincipalToken Name: "+userToken.getName());
////		log.info("UserPrincipalToken Authorities: "+userToken.getAuthorities());
////		log.info("UserPrincipalToken Details: "+userToken.getDetails());
////		log.info("UserPrincipalToken Principal: "+userToken.getPrincipal());
////		log.info("UserPrincipalToken Credentials: "+userToken.getCredentials());
//
//		AuthenticationHelper authenHelper = new AuthenticationHelper();
//		PasswordConstants passwordConstants = (PasswordConstants)request.getSession().getAttribute(UI_Constants.SESS_ATTR_PASSWORD_CONSTANTS);
//
//		//Get logged user				
//		UserProfile loggedUser = (UserProfile)request.getSession().getAttribute(UI_Constants.SESS_ATTR_LOGGED_USER);
//		if(!loggedUser.isKbankUser()) {
//		
//			//chain request
//			String requestURI = request.getRequestURI();
//			log.info("Request URI: " + request.getMethod() + " [" + requestURI + "]");
//			if (request.getSession().getAttribute(UI_Constants.SESS_ATTR_PASSWD_POLICY_PASSED) != Boolean.TRUE) {
//				
//				if (!(requestURI.indexOf(URI_KBOND_CHANGEPASSWORD) > -1) 
//						&& !(requestURI.indexOf(URI_KBOND_CHANGEPASSWORD_SUBMIT) > -1)
//						&& !(requestURI.indexOf(URI_KBOND_LOAD_ACTIVE_ALERT) > -1)){
//					
//					String log_info = "";
//					Date today = CommonHelper.currentDateTime().getTime();
//					int differ = 0;
//					//Is login first time
//					if (loggedUser.getLastSignIn() == null) {
//						//start date must not null
//						if (loggedUser.getStartDate() != null) {
//							//new or reset user (before or after 30 days), fwd to changePassword
//							differ = authenHelper.getDifferDay(today, loggedUser.getStartDate());
//							if (differ <= passwordConstants.getAccountActivationPeriod()) {
//								log.warn("First time login. Force to change password");
//								
//								request.getSession().setAttribute(UI_Constants.SESS_ATTR_PASSWD_POLICY_PASSED, Boolean.FALSE);
//								
//								response.sendRedirect(request.getContextPath()+URI_KBOND_CHANGEPASSWORD);
//								
//								return;							
//							} else {
//								//differ > passwordConstants.getAccountActivationPeriod()							
//								try {
//									/*loggedUser.setActive(UserProfile.ENABLED_NO);
//									loggedUser.setLoginFail(0);
//									loggedUser.setUpdateDate(today);*/
//									
//									UserProfileBean userProfileBean = new UserProfileBean();
//			    					userProfileBean.setLoginFail(0);
//			    					userProfileBean.setLocked(UserProfile.LOCKED_YES);
//			    					userProfileBean.setLastUpdate(today);
//			    					userProfileBean.setUsername(loggedUser.getUsername());
//			    					MiddlewareResponse result = userProfileService.updateUserProfileForLogin(userProfileBean);
//									
//			    					log_info = "Login failed, Account not activated within "+passwordConstants.getAccountActivationPeriod()+" days. Please contact system administrator";
//									log.error(log_info);
//									
//									request.getSession().invalidate();
//	//								request.setAttribute(UI_Constants.REQ_ATTR_ERRMSG, messageSource.getMessage("login.account.not.activated", new Object[] {passwordConstants.getAccountActivationPeriod()} , sessionLocale));
//	//								request.getRequestDispatcher(UI_Constants.URI_KBOND_LOGIN).forward(request, response);
//									response.sendRedirect(request.getContextPath()+UI_Constants.URI_KBOND_LOGIN+log_info);
//									return;								
//								} catch (Exception e) {
//									log.error(e);
//									request.getSession().invalidate();
//									log_info = "Login failed, Account not activated within "+passwordConstants.getAccountActivationPeriod()+" days. Please contact system administrator";
//									response.sendRedirect(request.getContextPath()+UI_Constants.URI_KBOND_LOGIN+log_info);
//									return;
//								}
//							}
//						} else {
//							//not ready, invalid user
//							log_info = "Login failed, User start date is null";
//							log.error(log_info);
//							request.getSession().invalidate();
//							response.sendRedirect(request.getContextPath()+UI_Constants.URI_KBOND_LOGIN+log_info);
//							return;
//						}						
//					} else {
//						//lastSignin != null, check signin after 60 days, fwd to changePassword.jsp
//						differ = authenHelper.getDifferDay(today, loggedUser.getLastSignIn());
//						if (differ > passwordConstants.getPasswordExpiredAfterLastSignIn()) {
//							log.warn("Login after last signin more than "+passwordConstants.getPasswordExpiredAfterLastSignIn()+" days ["+differ+"]. Force to change password");
//							
//	//						request.getSession().setAttribute(UI_Constants.REQ_ATTR_ERRMSG, messageSource.getMessage("login.password.expired.last.sigin", new Object[] {passwordConstants.getPasswordExpiredAfterLastSignIn(), differ} , sessionLocale));
//							request.getSession().setAttribute(UI_Constants.SESS_ATTR_PASSWD_POLICY_PASSED, Boolean.FALSE);
//							request.getSession().setAttribute(UI_Constants.SESS_ATTR_LOGGED_USER, loggedUser);
//	
//							response.sendRedirect(request.getContextPath()+URI_KBOND_CHANGEPASSWORD);
//							
//							return;
//						}									
//						
//					}
//					
//					//Check password is expired, get reminder
//					if (loggedUser.isPasswordExpired()) {
//						log.warn("Password is expired. Force to change password");
//	//					request.getSession().invalidate();
//						
//	//					request.getSession().setAttribute(UI_Constants.REQ_ATTR_ERRMSG, messageSource.getMessage("login.password.expired", null , sessionLocale));
//						request.getSession().setAttribute(UI_Constants.SESS_ATTR_PASSWD_POLICY_PASSED, Boolean.FALSE);
//						request.getSession().setAttribute(UI_Constants.SESS_ATTR_LOGGED_USER, loggedUser);
//						
//						response.sendRedirect(request.getContextPath()+URI_KBOND_CHANGEPASSWORD);
//						
//						return;
//					} else {
//						if (loggedUser.getExpiryDate() != null) {
//							differ = authenHelper.getDifferDay(loggedUser.getExpiryDate(), today);
//							if (differ <= 0) {
//								//set password expired = true
//								try {
//									/*loggedUser.setPasswordExpired(Boolean.TRUE);
//									loggedUser.setLoginFail(0);
//									loggedUser.setUpdateDate(today);
//									userAccessDAO.updateUser(loggedUser);*/
//									
//									UserProfileBean userProfileBean = new UserProfileBean();
//			    					userProfileBean.setLoginFail(0);
//			    					userProfileBean.setLastUpdate(today);
//			    					userProfileBean.setPasswordExpired(Boolean.TRUE);
//			    					userProfileBean.setUsername(loggedUser.getUsername());
//			    					MiddlewareResponse result = userProfileService.updateUserProfileForLogin(userProfileBean);
//									
//									log.warn("Password is expired. Force to change password");
//	//								request.getSession().invalidate();
//									
//	//								request.getSession().setAttribute(UI_Constants.REQ_ATTR_ERRMSG, messageSource.getMessage("login.password.expired", null , sessionLocale));
//									request.getSession().setAttribute(UI_Constants.SESS_ATTR_PASSWD_POLICY_PASSED, Boolean.FALSE);
//									request.getSession().setAttribute(UI_Constants.SESS_ATTR_LOGGED_USER, loggedUser);
//	
//									response.sendRedirect(request.getContextPath()+URI_KBOND_CHANGEPASSWORD);
//									
//									return;
//								} catch (Exception e) {
//									log.error(e);
//									request.getSession().invalidate();
//									log_info = "Login failed, "+e.getClass()+" "+e.getMessage();
//									response.sendRedirect(request.getContextPath()+UI_Constants.URI_KBOND_LOGIN+log_info);
//									return;
//								}
//							} else if (differ <= passwordConstants.getPasswordExpiredReminder()) {
//								log.warn("Your password will expire in "+differ+" days at "+loggedUser.getExpiryDate());
//	//							request.getSession().setAttribute("PasswordExpiredReminder", messageSource.getMessage("login.password.expired.reminder", new Object[] {differ} , sessionLocale));
//							} else {
//								//no reminder
//								log.info("Password will expire in "+differ+" days, No reminder message");
//							}
//						} else {
//							//not ready, invalid user
//							log_info = "Login failed, User Expiry Date is null";
//							log.error(log_info);
//							request.getSession().invalidate();
//							response.sendRedirect(request.getContextPath()+UI_Constants.URI_KBOND_LOGIN+log_info);
//							return;
//						}
//					}
//					
//					try {
//						/*//Save userAccess, update to DB
//						UserAccess userAccess = userAccessDAO.saveAndGetUserAccess(loggedUser, request);
//						loggedUser.setUserAccess(userAccess);					
//						request.getSession().setAttribute(UI_Constants.SESS_ATTR_USER_ACCESS, userAccess);
//						userAccess = null;*/
//	
//						//Save user
//						/*loggedUser.setLastSignIn(today);
//						loggedUser.setLoginFail(0);
//						userAccessDAO.updateUser(loggedUser);	*/
//						
//						UserProfileBean userProfileBean = new UserProfileBean();
//						userProfileBean.setLoginFail(0);
//						userProfileBean.setLastUpdate(today);
//						userProfileBean.setLastSignIn(today);
//						userProfileBean.setUsername(loggedUser.getUsername());
//						MiddlewareResponse result = userProfileService.updateUserProfileForLogin(userProfileBean);
//	
//						log.info("Post-authentication finish, Resolve User ID: " + loggedUser.getUserId());
//	
//						request.getSession().setAttribute(UI_Constants.SESS_ATTR_PASSWD_POLICY_PASSED, Boolean.TRUE);
//	//					request.getSession().setAttribute(UI_Constants.SESS_ATTR_LOGGED_USER_LAST_LOGIN, loggedUser.getLastSignIn());
//						request.getSession().setAttribute(UI_Constants.SESS_ATTR_LOGGED_USER, loggedUser);
//	
//						
//					} catch (Exception e) {
//						// TODO Auto-generated catch block
//						log_info = e.getMessage();
//						log.error(e,e);
//						request.getSession().invalidate();
//						response.sendRedirect(request.getContextPath()+UI_Constants.URI_KBOND_LOGIN+log_info);
//	//					request.getRequestDispatcher(UI_Constants.URI_KBOND_LOGIN).forward(request, response);
//						return;
//					}		
//					
//				}else {
//					//continue to next chain
//				}
//			}else {
//				//continue to next chain
//			}
//		}
//		arg2.doFilter(request, response);
//	}
//	
//	public void init(FilterConfig config) {
//		WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
//		userProfileService = (UserProfileService)springContext.getBean("userProfileService");
//	}
//
//}
